const ChatDao = require('../dao/chatDao');
const ChatPeopleDao = require('../dao/chatPeopleDao');
const ChatContentDao = require('../dao/chatContentDao');
const UserDao = require('../dao/userDao');
const FriendDao = require('../dao/friendDao');
const UserRightsDao = require('../dao/userRightsDao');
exports.create = function (params) {
    return new Promise(function (resolve, reject) {
        mysqlHelper.getConn()
            .then(function (conn) {
                UserRightsDao.queryRights(conn, params)
                    .then(function (result) {
                        if (result.length > 0 && result[0].RightsChat == 'T')
                            return conn.openTransaction();
                        throw {code: 400};
                    })
                    .then(function () {
                        return ChatDao.hasChat(conn, params);
                    })
                    .then(function (hasChatResult) {
                        if (hasChatResult.length > 0) {
                            ChatPeopleDao.updateChatPeople(conn, {
                                updateObj: {
                                    NewMsg: "T"
                                },
                                ChatNo: params.ChatNo,
                                openid: params.openid
                            })
                                .then(function (result) {
                                    return ChatContentDao.createChatContent(conn, {
                                        ChatNo: params.ChatNo,
                                        openid: params.openid,
                                        ChatContent: params.ChatContent,
                                        CreatedAt: new Date()
                                    });
                                })
                                .then(function () {
                                    return ChatDao.updateChat(conn, {
                                        ChatNo: params.ChatNo,
                                        CreatedAt: new Date()
                                    });
                                })
                                .then(function (result) {
                                    return conn.commitTransaction();
                                }, function (err) {
                                    conn.rollbackTransaction();
                                    throw err;
                                })
                                .then(function () {
                                    conn.releaseConn();
                                    resolve("发送成功");
                                    /*weChatApi.sendText(params.ToOpenId, "你有好友消息，请及时<a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxecae704ec4ae66da&redirect_uri=http%3A%2F%2Fhl.ileadtek.com%2Fwebroot%2Fmessage_friends.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'>查看</a>", function (err, result) {
                                        console.log("=sendMsg sendText err=", err);
                                        console.log("=sendMsg sendText result=", result);
                                    });*/
                                    getIsOnline(params.ToOpenId,function (err,result) {
                                        console.log("getIsOnline=result1=====================", result)
                                        if(err){
                                            console.log("getIsOnline=err====================",err);
                                        }else{
                                            console.log("getIsOnline=code========================",result.code);
                                            if(result.code === 1){
                                                console.log("getIsOnline=test========================",result.pushNum===1, (result.pushNum%10), (result.pushNum%10) === 0);
                                                if(result.pushNum===1 || (result.pushNum%10) === 0 ){
                                                    weChatApi.sendText(params.ToOpenId, "你有好友消息，请及时 <a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxecae704ec4ae66da&redirect_uri=http%3A%2F%2Fhl.ileadtek.com%2Fwebroot%2Fmessage_friends.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'>查看</a>", function (err, result) {
                                                        console.log("=sendMsg sendText err=", err);
                                                        console.log("=sendMsg sendText result=", result);
                                                    });
                                                }
                                            }
                                        }
                                    })
                                }, function (err) {
                                    console.log(err);
                                    conn.releaseConn();
                                    reject(err)
                                });
                        } else {
                            ChatDao.createChat(conn, {CreatedAt: new Date(), ChatNo: params.ChatNo})
                                .then(function (result) {
                                    return ChatPeopleDao.createChatPeople(conn, [
                                        [params.ChatNo, params.openid, "T"],
                                        [params.ChatNo, params.ToOpenId, "F"]
                                    ]);
                                })
                                .then(function (result) {
                                    return ChatContentDao.createChatContent(conn, {
                                        ChatNo: params.ChatNo,
                                        openid: params.openid,
                                        ChatContent: params.ChatContent,
                                        CreatedAt: new Date()
                                    });
                                })
                                .then(function () {
                                    return ChatDao.updateChat(conn, {
                                        ChatNo: params.ChatNo,
                                        CreatedAt: new Date()
                                    });
                                })
                                .then(function (result) {
                                    return conn.commitTransaction();
                                }, function (err) {
                                    conn.rollbackTransaction();
                                    throw err;
                                })
                                .then(function () {
                                    conn.releaseConn();
                                    resolve("发送成功");
                                    /*weChatApi.sendText(params.ToOpenId, "你有好友消息，请及时<a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxecae704ec4ae66da&redirect_uri=http%3A%2F%2Fhl.ileadtek.com%2Fwebroot%2Fmessage_friends.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'>查看</a>", function (err, result) {
                                        console.log("=sendMsg sendText err=", err);
                                        console.log("=sendMsg sendText result=", result);
                                    });*/
                                    getIsOnline(params.ToOpenId,function (err,result) {
                                        console.log("getIsOnline=result2=====================", result)
                                        if(err){
                                            console.log("getIsOnline=err====================",err);
                                        }else{
                                            console.log("getIsOnline=code========================",result.code);
                                            if(result.code === 1){
                                                console.log("getIsOnline=test========================",result.pushNum===1, (result.pushNum%10), (result.pushNum%10) === 0);
                                                if(result.pushNum===1 || (result.pushNum%10) === 0 ){
                                                    weChatApi.sendText(params.ToOpenId, "你有好友消息，请及时 <a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxecae704ec4ae66da&redirect_uri=http%3A%2F%2Fhl.ileadtek.com%2Fwebroot%2Fmessage_friends.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'>查看</a>", function (err, result) {
                                                        console.log("=sendMsg sendText err=", err);
                                                        console.log("=sendMsg sendText result=", result);
                                                    });
                                                }
                                            }
                                        }
                                    })
                                }, function (err) {
                                    console.log(err);
                                    conn.releaseConn();
                                    reject(err)
                                });
                        }
                    }, function (err) {
                        reject(err);
                    });
            });
    });
};
exports.list = function (params) {
    return new Promise(function (resolve, reject) {
        let chatList = {};
        UserDao.queryUserDetail(masterPool, params)
            .then(function (result) {
                return ChatDao.selectChat(masterPool, {params: params, selfInfo: result[0]}, true)
            })
            .then(function (result) {
                chatList = result;
                return Promise.all(selectLastMsg(chatList))
            })
            .then(function (result) {
                chatList.data = result;
                return chatList;
            })
            .then(resolve, reject)
    });
    function selectLastMsg(chatList) {
        let selectArr = [];
        for (let i in chatList.data) {
            let item = chatList.data[i];
            selectArr.push(ChatContentDao.selectLastContent(masterPool, {ChatNo: item.ChatNo}).then(function (lastMsg) {
                item.LastMsg = lastMsg;
                return item;
            }));
        }
        return selectArr;
    }
};
exports.recordList = function (params) {
    return new Promise(function (resolve, reject) {
        let chatInfo = {};
        ChatPeopleDao.hasSeen(masterPool, params)
            .then(function () {
                return ChatContentDao.selectChatContent(masterPool, params, true);
            })
            .then(function (result) {
                chatInfo = result
                return FriendDao.queryFriendInfo(masterPool, params);
            })
            .then(function (result) {
                if (result.length > 0) chatInfo.EvaluatePoint = result[0].EvaluatePoint;
                else chatInfo.EvaluatePoint = 0;
                return ChatContentDao.countChatContent(masterPool, {ChatNo: params.ChatNo, openid: params.TaOpenId});
            })
            .then(function (result) {
                chatInfo.TaReplyNum = result;
                return chatInfo;
            })
            .then(resolve, reject)
    });
};
const request = require('request');
function getIsOnline(openid,cb) {
    request({
        uri: 'http://' + config.host + ':3009/user/isOnline',
        headers: {"Content-Type": "application/json",},
        method: "post",
        body: JSON.stringify({openid:openid})
    },function (err, response, body) {
        printLog("=requestToWeChat=",body);
        if (err) {
            cb(err);
        } else {
            cb(null,JSON.parse(body));
        }
    })
}